<template>
  <div>
    <el-form label-width="auto" style="margin-top: 20px">
      <el-form-item label="设置名">
        <el-col :span="12">
          <el-input v-model="settings.name" />
        </el-col>
        <el-col :span="12">
          <el-dropdown class="ml-4" split-button type="primary" @click="saveSettings">
            <span>
              <el-icon><set-up /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item
                  v-for="item in savedSettingNames"
                  :key="item"
                  @click="getSettingData(item)"
                >
                  {{ item }}
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </el-col>
      </el-form-item>
      <!-- 标识符设置 -->
      <el-form-item label="标识符">
        <el-button-group>
          <el-button @click="idColumnIdentifiersVisible = true">样本ID</el-button>
          <el-button @click="fieldColumnIdentifiersVisible = true">字段名</el-button>
          <el-button @click="valueColumnIdentifiersVisible = true">字段值</el-button>
          <el-button @click="valueToRemoveColumnIdentifiersVisible = true">删除值</el-button>
          <el-button @click="extraColumnIdentifiersVisible = true">其他</el-button>
        </el-button-group>
      </el-form-item>
      <!-- ID字段名 -->
      <el-form-item label="ID字段名">
        <el-input v-model="settings.idFieldName" />
      </el-form-item>
      <!-- 字符串ID -->
      <el-form-item label="字符串ID">
        <el-switch v-model="settings.isTextId" inline-prompt active-text="是" inactive-text="否" />
      </el-form-item>
      <!-- 脚本列名 -->
      <el-form-item label="脚本列名">
        <el-input v-model="settings.scriptColumnHeader" />
      </el-form-item>
      <!-- 额外条件的逻辑类型 -->
      <el-form-item label="额外列逻辑">
        <el-radio-group v-model="settings.extraLogic">
          <el-radio-button label="AND" value="AND" />
          <el-radio-button label="OR" value="OR" />
        </el-radio-group>
      </el-form-item>
      <!-- 分类更新类型 -->
      <el-form-item label="分类更新类型">
        <el-radio-group v-model="settings.categoricalUpdateKind">
          <el-radio-button label="APPEND" value="APPEND" />
          <el-radio-button label="RESET" value="RESET" />
        </el-radio-group>
      </el-form-item>
      <!-- 是否创建数据表 -->
      <el-form-item label="创建数据表">
        <el-switch v-model="settings.buildDataTable" />
      </el-form-item>
      <!-- 数据表配置 -->
      <!-- 保留小数位数 -->
      <el-form-item label="小数位数">
        <el-slider
          :min="0"
          :max="10"
          :disabled="!settings.buildDataTable"
          v-model="settings.dataTable.decimalPlaces"
          style="max-width: 200px; margin-left: 4px"
        />
      </el-form-item>
      <!-- 添加百分比 -->
      <el-form-item label="添加百分比">
        <el-switch
          v-model="settings.dataTable.addPercentage"
          :disabled="!settings.buildDataTable"
        />
      </el-form-item>
      <!-- 数据表页名 -->
      <el-form-item label="数据表页名">
        <el-input
          v-model="settings.dataTable.resultPageName"
          :disabled="!settings.buildDataTable"
        />
      </el-form-item>
    </el-form>

    <!-- dialogs -->
    <!-- 保存为默认值对话框 -->
    <el-dialog v-model="yesOrNoDialogVisible" title="保存" width="400">
      <span>{{ yesOrNoDialogText }}</span>
      <template #footer>
        <el-button @click="onYesOrNoButtonClick(false)">否</el-button>
        <el-button @click="onYesOrNoButtonClick(true)" type="primary">是</el-button>
      </template>
    </el-dialog>
    <!-- 关闭时，如果属性发生了变化，并且尚未保存，提示对话框 -->
    <el-dialog v-model="isChangedNoticeVisible" title="注意" width="400">
      <span>设置已经改变，是否保存？所有未保存的设置都将丢失。</span>
      <el-button>否</el-button>
      <el-button @click="saveSettings" type="primary">是</el-button>
    </el-dialog>
    <!-- ID列标识符对话框 -->
    <el-dialog v-model="idColumnIdentifiersVisible" title="ID列标识符">
      <el-input
        v-model="settings.identifiers.id"
        type="textarea"
        style="max-width: 300px"
        :autosize="{ minRows: 5, maxRows: 15 }"
      />
    </el-dialog>
    <!-- 字段列标识符 -->
    <el-dialog v-model="fieldColumnIdentifiersVisible" title="字段列标识符">
      <el-input
        v-model="settings.identifiers.field"
        type="textarea"
        style="max-width: 300px"
        :autosize="{ minRows: 5, maxRows: 15 }"
      />
    </el-dialog>
    <!-- 字段值标识符 -->
    <el-dialog v-model="valueColumnIdentifiersVisible" title="字段值列标识符">
      <el-input
        v-model="settings.identifiers.value"
        type="textarea"
        style="max-width: 300px"
        :autosize="{ minRows: 5, maxRows: 15 }"
      />
    </el-dialog>
    <!-- 移除值标识符 -->
    <el-dialog v-model="valueToRemoveColumnIdentifiersVisible" title="删除值列标识符">
      <el-input
        v-model="settings.identifiers.valueToRemove"
        type="textarea"
        style="max-width: 300px"
        :autosize="{ minRows: 5, maxRows: 15 }"
      />
    </el-dialog>
    <!-- 其他列标识符 -->
    <el-dialog v-model="extraColumnIdentifiersVisible" title="其他列标识符">
      <el-input
        v-model="settings.identifiers.extra"
        type="textarea"
        style="max-width: 300px"
        :autosize="{ minRows: 5, maxRows: 15 }"
      />
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref, watch } from 'vue'
import type { Settings, WebCommands } from './types'
import {
  ElButton,
  ElButtonGroup,
  ElCol,
  ElDialog,
  ElDropdown,
  ElDropdownItem,
  ElDropdownMenu,
  ElForm,
  ElFormItem,
  ElIcon,
  ElInput,
  ElRadioGroup,
  ElRadioButton,
  ElSlider,
  ElSwitch,
  ElMessage,
} from 'element-plus'
import { SetUp } from '@element-plus/icons-vue'

const defaultSettingName = '默认'
// 提醒保存默认
const saveAsDefaultMessage = '是否保存为默认设置？'
const coverDefaultMessage = '是否覆盖默认设置？'
const yesOrNoDialogText = ref(saveAsDefaultMessage)
// 保存的配置
const savedSettingNames = ref<string[]>([defaultSettingName])
// 记录是否按了 '是' 按钮
let clickedYesButton = false
// 配置对象
const settings = ref<Settings>({
  name: '',
  identifiers: {
    id: '',
    field: '',
    value: '',
    valueToRemove: '',
    extra: '',
  },
  idFieldName: '',
  isTextId: false,
  scriptColumnHeader: 'SQL_SCRIPT',
  extraLogic: 'AND',
  categoricalUpdateKind: 'APPEND',
  buildDataTable: false,
  dataTable: {
    addPercentage: false,
    decimalPlaces: 0,
    resultPageName: 'SQL_TABLE',
  },
})

// 当前设置对象是否被修改
let isChanged = false
const isChangedNoticeVisible = ref(false)
// 保存设置对话框
const yesOrNoDialogVisible = ref(false)
// 是否保存为默认
const saveAsDefault = ref(false)
// "是"、"否" 按钮回调
function onYesOrNoButtonClick(value: boolean) {
  if (yesOrNoDialogText.value === saveAsDefaultMessage) {
    saveAsDefault.value = value
  }
  yesOrNoDialogVisible.value = false
  clickedYesButton = value
}

// 标识符设置对话框
const idColumnIdentifiersVisible = ref(false)
const fieldColumnIdentifiersVisible = ref(false)
const valueColumnIdentifiersVisible = ref(false)
const valueToRemoveColumnIdentifiersVisible = ref(false)
const extraColumnIdentifiersVisible = ref(false)

// 添加接收信息回调函数
window.chrome?.webview?.addEventListener('message', (event) => {
  const data = event.data as { type?: WebCommands; data?: unknown }
  if (!data.type) {
    return
  }
  // 处理回调
  switch (data.type) {
    case 'setSettingList': {
      const nameList = data.data as string[]
      if (nameList) {
        savedSettingNames.value.splice(0)
        savedSettingNames.value.push(...nameList)
      }
      break
    }
    case 'setSettingData': {
      const settingData = data.data as Settings
      if (settingData) {
        settings.value = settingData
        // 添加到设置列表中
        if (
          settingData.name !== defaultSettingName &&
          !savedSettingNames.value.find((e) => e.toLowerCase() === settingData.name.toLowerCase())
        ) {
          savedSettingNames.value.push(settingData.name)
        }
      }
      break
    }
    case 'getSettingData': {
      window.chrome?.webview?.postMessage({
        type: 'setSettingData',
        data: settings.value,
      })
      break
    }
    case 'message': {
      const msg = data.data as { text: string; type: 'error' | 'warning' | 'info' | 'success' }
      if (msg) {
        ElMessage({ type: msg.type, message: msg.text })
      }
      break
    }
  }
})

// 载入完成时，拉取设置列表
onMounted(() => {
  // 拉取设置名
  getSettingList()
  // 加载默认设置
  getSettingData(defaultSettingName)
})
// 当窗口关闭时，检查设置是否被改变，如果改变，则提示窗口
window.chrome?.webview?.addEventListener(
  'beforeunload',
  () => (isChangedNoticeVisible.value = isChanged),
)

// 向WebView请求拉取设置名列表
function getSettingList() {
  window.chrome?.webview?.postMessage({
    type: 'getSettingList',
  })
}

// 监听属性变化
watch(
  settings,
  () => {
    isChanged = true
  },
  { deep: true } /** 深度监听 */,
)

// 保存当前页面的设置信息
watch(yesOrNoDialogVisible, (value) => {
  // 只关注对话框关闭
  if (value || !clickedYesButton) {
    return
  }
  // 向WebView请求保存
  window.chrome?.webview?.postMessage({
    type: saveAsDefault.value ? 'saveSettingAsDefault' : 'saveSetting',
    data: settings.value,
  })
  // 检查设置名是否已存在
  if (!savedSettingNames.value.find((e) => e.toLowerCase() === settings.value.name.toLowerCase())) {
    savedSettingNames.value.push(settings.value.name)
  }
  // 更新为默认名称
  settings.value.name = defaultSettingName
  // 重设保存默认值为 false
  saveAsDefault.value = false
  // 重新设置按钮记录
  clickedYesButton = false
})

function saveSettings() {
  const name = settings.value.name.trim()
  // 如果未指定命名，弹出提醒
  if (name.length === 0) {
    ElMessage({ message: '未指定设置名称', type: 'warning' })
    return
  }
  // 如果命名不是默认名，提示是否保存为默认
  if (name !== defaultSettingName) {
    yesOrNoDialogText.value = saveAsDefaultMessage
  } else {
    yesOrNoDialogText.value = coverDefaultMessage
  }
  yesOrNoDialogVisible.value = true
}

// 向WebView请求拉取指定设置
function getSettingData(name: string) {
  window.chrome?.webview?.postMessage({
    type: 'getSettingData',
    data: name,
  })
}
</script>

<style lang="css">
.ml-4 {
  margin-left: 4px;
}
</style>
